 #include "listview.h"
#include <QDrag>
#include <QDragMoveEvent>
#include <QMimeData>
#include <QStandardItemModel>
#include "thumbnail.h"
#include <QDebug>
#include <QApplication>
#include "stepbase.h"
ListView::ListView(QWidget *parent) : QListView(parent)
{
    setAcceptDrops(true);

    setStyleSheet("border:none;");
}
//记录拖拽初始位置
void ListView::mousePressEvent(QMouseEvent *event)
{
    QListView::mousePressEvent(event);
    if(event->buttons() & Qt::LeftButton){
        startPos = event->pos();
    }
}

void ListView::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons() & Qt::LeftButton){
        if((event->pos() - startPos).manhattanLength() < QApplication::startDragDistance()) return;

        QModelIndex theDragIndex = indexAt(startPos);

        theDragRow = theDragIndex.row();

        QStandardItemModel *listModel = qobject_cast<QStandardItemModel *>(model());
        QStandardItem *theDragItem = listModel->item(theDragRow);
        if(!theDragItem)
        {
            return;
        }

//[1]把拖拽数据放在QMimeData容器中
        QString text = theDragItem->text();
        QIcon icon = theDragItem->icon();
        QByteArray itemData;
        QDataStream dataStream(&itemData, QIODevice::WriteOnly);
        StepData data = theDragItem->data(Qt::UserRole+1).value<StepData>();

        dataStream<<data.m_text << data.m_pix << data.m_stepType;
        QMimeData *mimeData = new QMimeData;
        mimeData->setData(myMimeType(),itemData/* theDragItem->data(Qt::UserRole+1).toByteArray()*/);
//[1]

//[2]设置拖拽时的缩略图
        thumbnail *DragImage = new thumbnail(this);
        DragImage->setupthumbnail(icon, text);
        //DragImage->setIconSize(18);  //default:20
        QPixmap pixmap = DragImage->grab();

        QDrag *drag = new QDrag(this);
        drag->setMimeData(mimeData);
        drag->setPixmap(pixmap);
        drag->setHotSpot(QPoint(pixmap.width() / 2, pixmap.height() / 2));
//[2]
        if(drag->exec(Qt::MoveAction) == Qt::MoveAction){

        }
    }
}

void ListView::dragEnterEvent(QDragEnterEvent *event)
{
    ListView *source = qobject_cast<ListView *>(event->source());
    if (source && source == this) {
        event->setDropAction(Qt::MoveAction);
        event->accept();
    }
}

void ListView::dragLeaveEvent(QDragLeaveEvent *event)
{

    event->accept();
}

void ListView::dragMoveEvent(QDragMoveEvent *event)
{
    ListView *source = qobject_cast<ListView *>(event->source());
    if (source && source == this) {

        event->setDropAction(Qt::MoveAction);
        event->accept();
    }
}

void ListView::dropEvent(QDropEvent *event)
{
    ListView *source = qobject_cast<ListView *>(event->source());
    if (source && source == this){

        event->setDropAction(Qt::MoveAction);
        event->accept();
    }
}
